<template>
  <div :id="playerId">
    <!--    <div  class="prism-player" id="J_prismPlayer"></div>-->
  </div>
</template>

<script>
import {ref} from "vue";
import axios from "axios";

export default {
  exposed: ['playUrl', 'playVod'], // 重点：需要暴露 气死我了
  name: 'player',
  props: {
    playerId: {
      default: "player-div"
    },
  },
  setup(props) {
    const aliPlayer = ref();

    /**
     * 根据url播放
     * @param url
     */
    const playUrl = (url) => {
      console.log("开始播放:", url);

      //如果已经有播放器了，则将播放器div删除
      if (aliPlayer.value) {
        aliPlayer.value = null;
        $("#" + props.playerId + '-player').remove();
      }

      // 初始化播放器
      $("#" + props.playerId).append("<div class=\"prism-player\" id=\"" + props.playerId + "-player\"></div>");
      aliPlayer.value = new Aliplayer({
        id: props.playerId + '-player',
        width: '100%',
        autoplay: false,
        source: url,
        cover: 'http://liveroom-img.oss-cn-qingdao.aliyuncs.com/logo.png',
      }, function (player) {
        console.log('播放器创建好了。')
      });
    }

    /**
     * 根据视频点播授权码播放视频
     * @param vod 视频id
     * @returns {{playUrl: playUrl}}
     */
    const playVod = (vod) => {
      axios.get(process.env.VUE_APP_SERVER + '/file/web/get-auth/' + vod).then((response) => {
        let resp = response.data;
        if (resp.success) {
          //如果已经有播放器了，则将播放器div删除
          if (aliPlayer.value) {
            aliPlayer.value = null;
            $("#" + props.playerId + '-player').remove();
          }

          // 初始化播放器
          $("#" + props.playerId).append("<div class=\"prism-player\" id=\"" + props.playerId + "-player\"></div>");
          aliPlayer.value = new Aliplayer({
            id: props.playerId + '-player',
            width: '100%',
            autoplay: true,
            vid: vod,
            playauth: resp.content,
            cover: 'http://liveroom-img.oss-cn-qingdao.aliyuncs.com/logo.png',
            encryptType: 1, //当播放私有加密流时需要设置。
          }, function (player) {
            console.log('播放器创建好了。')
          });
        } else {
          Toast.warning('播放错误。')
        }
      })
    }

    return {
      playUrl,
      playVod
    }
  }
}
</script>